package com.lexue.articlesync.adapter.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lexue.articlesync.adapter.AbstractPlatformAdapter;
import com.lexue.articlesync.entity.Article;
import com.lexue.articlesync.entity.Video;
import com.lexue.articlesync.entity.PlatformAuth;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Component;

/**
 * B站平台适配器
 */
@Slf4j
@Component
public class BilibiliAdapter extends AbstractPlatformAdapter {
    
    private static final String PLATFORM_CODE = "bilibili";
    private static final String PLATFORM_NAME = "哔哩哔哩";
    
    // B站API端点
    private static final String API_BASE_URL = "https://member.bilibili.com";
    private static final String VIDEO_UPLOAD_URL = API_BASE_URL + "/x/vu/web/add";
    private static final String AUTH_CHECK_URL = API_BASE_URL + "/x/web/nav";
    
    @Override
    public String getPlatformCode() {
        return PLATFORM_CODE;
    }
    
    @Override
    public String getPlatformName() {
        return PLATFORM_NAME;
    }
    
    @Override
    public String[] getSupportedContentTypes() {
        return new String[]{"video"}; // B站主要支持视频
    }
    
    @Override
    public boolean validateAuth(PlatformAuth auth) {
        if (!super.validateAuth(auth)) {
            return false;
        }
        
        try {
            Request request = createRequestBuilder()
                    .url(AUTH_CHECK_URL)
                    .build();
            
            request = addAuthHeaders(request.newBuilder(), auth).build();
            
            try (Response response = executeRequest(request)) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    return jsonResponse.getIntValue("code") == 0;
                }
                return false;
            }
        } catch (Exception e) {
            log.error("验证B站认证失败", e);
            return false;
        }
    }
    
    @Override
    public PublishResult publishArticle(Article article, PlatformAuth auth, PublishOptions options) {
        // B站主要是视频平台，文章发布功能有限
        log.warn("B站不支持文章发布功能");
        return buildFailureResult("B站不支持文章发布功能");
    }
    
    @Override
    public PublishResult publishVideo(Video video, PlatformAuth auth, PublishOptions options) {
        validateRequired(video.getTitle(), "视频标题");
        validateRequired(video.getFilePath(), "视频文件");
        
        try {
            // 构建发布参数
            JSONObject publishData = new JSONObject();
            publishData.put("title", limitLength(options.getTitle() != null ? options.getTitle() : video.getTitle(), 80));
            publishData.put("desc", options.getContent() != null ? options.getContent() : video.getDescription());
            publishData.put("copyright", options.isOriginal() ? 1 : 2); // 1-原创，2-转载
            
            // 处理标签
            String tags = formatTags(options.getTags() != null ? options.getTags() : video.getTags());
            if (!tags.isEmpty()) {
                String[] tagArray = tags.split(",");
                publishData.put("tag", String.join(",", tagArray));
            }
            
            // 处理封面
            if (options.getCoverImage() != null) {
                publishData.put("cover", options.getCoverImage());
            }
            
            // 视频文件（实际应用中需要先上传到B站服务器）
            publishData.put("videos", video.getFilePath());
            
            // 分区设置（默认为生活区）
            publishData.put("tid", 21);
            
            // 发布时间设置
            if (options.isAutoPublish()) {
                publishData.put("open_elec", 1);
            }
            
            RequestBody body = RequestBody.create(
                    publishData.toJSONString(),
                    MediaType.parse("application/json; charset=utf-8")
            );
            
            Request request = createRequestBuilder()
                    .url(VIDEO_UPLOAD_URL)
                    .post(body)
                    .build();
            
            request = addAuthHeaders(request.newBuilder(), auth).build();
            
            try (Response response = executeRequest(request)) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    
                    if (jsonResponse.getIntValue("code") == 0) {
                        JSONObject data = jsonResponse.getJSONObject("data");
                        String contentId = data.getString("bvid");
                        String contentUrl = "https://www.bilibili.com/video/" + contentId;
                        
                        log.info("B站视频发布成功: {}", contentId);
                        return buildSuccessResult(contentId, contentUrl);
                    } else {
                        String errorMsg = jsonResponse.getString("message");
                        return buildFailureResult("B站发布失败: " + errorMsg);
                    }
                } else {
                    return buildFailureResult(handleErrorResponse(response));
                }
            }
            
        } catch (Exception e) {
            log.error("B站视频发布异常", e);
            return buildFailureResult("B站视频发布异常: " + e.getMessage());
        }
    }
    
    @Override
    public PublishStatus checkPublishStatus(String platformContentId, PlatformAuth auth) {
        try {
            String checkUrl = API_BASE_URL + "/x/web/archive/stat?bvid=" + platformContentId;
            
            Request request = createRequestBuilder()
                    .url(checkUrl)
                    .build();
            
            request = addAuthHeaders(request.newBuilder(), auth).build();
            
            try (Response response = executeRequest(request)) {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    JSONObject jsonResponse = JSON.parseObject(responseBody);
                    
                    if (jsonResponse.getIntValue("code") == 0) {
                        JSONObject data = jsonResponse.getJSONObject("data");
                        int state = data.getIntValue("state");
                        
                        switch (state) {
                            case 1: // 发布成功
                                return PublishStatus.SUCCESS;
                            case 0: // 审核中
                                return PublishStatus.REVIEWING;
                            case -1: // 审核不通过
                                return PublishStatus.FAILED;
                            default:
                                return PublishStatus.PROCESSING;
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("检查B站发布状态失败", e);
        }
        
        return PublishStatus.SUCCESS; // 默认返回成功
    }
}